package com.ruoyi.flowable.listener.move;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.policy.PictureRenderPolicy;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.equ.domain.EquAsset;
import com.ruoyi.equ.domain.EquMove;
import com.ruoyi.equ.domain.EquRepair;
import com.ruoyi.equ.service.IEquAssetService;
import com.ruoyi.equ.service.IEquMoveService;
import com.ruoyi.flowable.domain.WorkOrderAssetRel;
import com.ruoyi.flowable.service.IWorkOrderAssetRelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.ruoyi.flowable.listener.asset.AssetCompleteListener.*;

/**
 * 移动-完成监听
 */
@Slf4j
@Component("moveCompleteListener")
public class MoveCompleteListener implements ExecutionListener {
    private static final IEquMoveService moveService = SpringUtils.getBean(IEquMoveService.class);
    private static final IEquAssetService assetService = SpringUtils.getBean(IEquAssetService.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final IWorkOrderAssetRelService workOrderAssetRelService = SpringUtils.getBean(IWorkOrderAssetRelService.class);


    @Override
    public void notify(DelegateExecution execution) {
        try {
            String assetName = execution.getVariable("assetName", String.class);
            String moveType = execution.getVariable("moveType", String.class);
            EquMove equMove = execution.getVariable("equMove", EquMove.class);
            Date closeTime = sdf.parse(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            equMove.setFinishTime(closeTime);
            equMove.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            equMove.setRemark(assetName + moveType);
            moveService.insertEquMove(equMove);

            //资产更新移入科室、移入地点
            Long assetId = Long.valueOf(execution.getVariable("assetId", String.class));
            EquAsset equAsset = new EquAsset();
            equAsset.setAssetId(assetId);
            //维修不用更改
            if (!moveType.equals("维修搬运")) {
                equAsset.setUseDept(execution.getVariable("toDept", String.class));
                equAsset.setStorageLocation(execution.getVariable("toLocation", String.class));
            }
            assetService.updateEquAsset(equAsset);

            //更新状态
            String processInstanceId = execution.getProcessInstanceId();
            WorkOrderAssetRel workOrderAssetRel = new WorkOrderAssetRel();
            workOrderAssetRel.setProcInsId(processInstanceId);
            workOrderAssetRel.setWorkOrderStatus("已完成");
            workOrderAssetRel.setFinishTime(new Date());
            //生成word
            String url = generateWord(execution.getVariables(), equMove);
            workOrderAssetRel.setFileUrl(url);
            workOrderAssetRelService.updateWorkOrderAssetRel(workOrderAssetRel);
        } catch (ParseException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String generateWord(Map<String, Object> variables, EquMove equMove) throws IOException {
        BufferedInputStream resourceAsStream = new BufferedInputStream(
                Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("word/医院设备移动申请表.docx"))
        );
        // 使用配置编译模板
        XWPFTemplate template = XWPFTemplate.compile(resourceAsStream);
        Configure config = template.getConfig();
        config.customPolicy("购买合同", new PictureRenderPolicy());

        HashMap<String, Object> finalMap = new HashMap<>();
        finalMap.put("申请单号", equMove.getMoveId());//move_id
        finalMap.put("申请日期", sdf.format(equMove.getCreateTime()));

        String moveType = variables.get("moveType").toString();
        if (moveType.equals("临时借用"))
            finalMap.put("移动类型1", "☑ 临时借用（预计归还日期：" + variables.get("returnDate") + "）");
        else finalMap.put("移动类型1", "□ 临时借用");
        if (moveType.equals("永久调拨")) finalMap.put("移动类型2", "☑");
        else finalMap.put("移动类型2", "□");
        if (moveType.equals("维修搬运")) finalMap.put("移动类型3", "☑");
        else finalMap.put("移动类型3", "□");
        if (moveType.equals("科室调整搬迁")) finalMap.put("移动类型4", "☑");
        else finalMap.put("移动类型4", "□");

        finalMap.put("设备名称", variables.get("assetName"));
        finalMap.put("设备型号规格", variables.get("modelSpec"));
        finalMap.put("资产编号", variables.get("assetNumber"));
        finalMap.put("生产厂家", variables.get("manufacturer"));
        finalMap.put("购置日期", variables.get("purchaseDate"));
        finalMap.put("已使用时长", variables.get("actualServiceTime"));
        finalMap.put("设备当前价值", variables.get("currentValue"));
        finalMap.put("设备重量", variables.get("weight"));
        finalMap.put("外形尺寸", variables.get("size"));
        List<String> specialAttr = (List<String>) variables.get("specialAttr");
        if (specialAttr.contains("精密仪器")) finalMap.put("特殊属性1", "☑");
        else finalMap.put("特殊属性1", "□");
        if (specialAttr.contains("电气设备")) finalMap.put("特殊属性2", "☑");
        else finalMap.put("特殊属性2", "□");
        if (specialAttr.contains("大型设备")) finalMap.put("特殊属性3", "☑");
        else finalMap.put("特殊属性3", "□");

        finalMap.put("移出科室", variables.get("fromDept"));
        finalMap.put("移出地点", variables.get("fromLocation"));
        finalMap.put("移出科室联系人", variables.get("fromContact"));
        finalMap.put("移出科室联系人联系电话", variables.get("fromPhone"));
        //维修移入科室就是自己
        if (moveType.equals("维修搬运")) {
            finalMap.put("移入科室", variables.get("fromDept"));
            finalMap.put("移入地点", variables.get("fromLocation"));
            finalMap.put("移入科室联系人", variables.get("fromContact"));
            finalMap.put("移入科室联系人联系电话", variables.get("fromPhone"));
        } else {
            finalMap.put("移入科室", variables.get("toDept"));
            finalMap.put("移入地点", variables.get("toLocation"));
            finalMap.put("移入科室联系人", variables.get("toContact"));
            finalMap.put("移入科室联系人联系电话", variables.get("toPhone"));
        }
        finalMap.put("计划移动时间", variables.get("planMoveTime"));
        finalMap.put("预计移动时长", variables.get("estimateDuration"));

        String moveReason = variables.get("moveReason").toString();
        if (moveReason.equals("临床需求调整")) finalMap.put("移动核心原因1", "☑");
        else finalMap.put("移动核心原因1", "□");
        if (moveReason.equals("科室业务扩展")) finalMap.put("移动核心原因2", "☑");
        else finalMap.put("移动核心原因2", "□");
        if (moveReason.equals("设备维修")) finalMap.put("移动核心原因3", "☑");
        else finalMap.put("移动核心原因3", "□");
        if (moveReason.equals("医院空间调整")) finalMap.put("移动核心原因4", "☑");
        else finalMap.put("移动核心原因4", "□");
        if (moveReason.equals("其他")) finalMap.put("移动核心原因5", "☑ 其他");
        else finalMap.put("移动核心原因5", "□ 其他");

        finalMap.put("补充说明移动原因", variables.get("moveReasonDesc"));

        List<String> specialNeeds = (List<String>) variables.get("specialNeeds");
        if (specialNeeds.contains("需专业搬运团队")){
            finalMap.put("特殊需求1", "☑ 需专业搬运团队（注明要求：" + variables.get("carriageReq") + "）");
        }
        else finalMap.put("特殊需求1", "□ 需专业搬运团队");
        if (specialNeeds.contains("需提前断电")){
            finalMap.put("特殊需求2", "☑ 需提前断电 / 拆线（断电时间：" + variables.get("powerOffTime") + "）");
        }
        else finalMap.put("特殊需求2", "□ 需提前断电 / 拆线");
        if (specialNeeds.contains("需校准调试")) {
            finalMap.put("特殊需求3", "☑ 需校准调试（移动后校准时间：" + variables.get("calibrateTime") + "）");
        }
        else finalMap.put("特殊需求3", "□ 需校准调试");
        if (specialNeeds.contains("需备用设备")) {
            finalMap.put("特殊需求4", "☑ 需备用设备支持（备用设备需求：" + variables.get("spareDevice") + "）");
        }
        else finalMap.put("特殊需求4", "□ 需备用设备支持");

        List<Map<String, String>> signature_act2 = (List<Map<String, String>>) variables.get("signature_act2");
        finalMap.put("移出审批人签字", Pictures.ofLocal(replaceUrl(signature_act2.get(0).get("url"))).size(200, 80).create());
        config.customPolicy("移出审批人签字", new PictureRenderPolicy());
        List<Map<String, String>> leaderSign_act2 = (List<Map<String, String>>) variables.get("leaderSign_act2");
        finalMap.put("移出负责人签字", Pictures.ofLocal(replaceUrl(leaderSign_act2.get(0).get("url"))).size(200, 80).create());
        config.customPolicy("移出负责人签字", new PictureRenderPolicy());
        finalMap.put("移出负责人签字日期", variables.get("date2_2"));

        //7_2_1、7_3、7_1
        //${moveType=="科室调整搬迁"}
        if (moveType.equals("科室调整搬迁")) {
            List<Map<String, String>> signature_act7_1 = (List<Map<String, String>>) variables.get("signature_act7_1");
            finalMap.put("移入验收人签字", Pictures.ofLocal(replaceUrl(signature_act7_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("移入验收人签字", new PictureRenderPolicy());
            List<Map<String, String>> leaderSign_act7_1 = (List<Map<String, String>>) variables.get("leaderSign_act7_1");
            finalMap.put("移入科室验收签字", Pictures.ofLocal(replaceUrl(leaderSign_act7_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("移入科室验收签字", new PictureRenderPolicy());
            finalMap.put("移入负责人签字日期", variables.get("date7_1"));

            finalMap.put("实际移动时间", variables.get("moveTime7_1").toString());
            finalMap.put("移动完成时间", variables.get("completeTime7_1").toString());

            List<Map<String, String>> signature_act4 = (List<Map<String, String>>) variables.get("signature_act4");
            finalMap.put("资产审批人签字", Pictures.ofLocal(replaceUrl(signature_act4.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("资产审批人签字", new PictureRenderPolicy());
            finalMap.put("资产签字日期", variables.get("date4"));

            //后勤保障部门意见
            String flag5 = variables.get("flag5").toString();
            if (StringUtils.isNotEmpty(flag5)) {
                //4.后勤保障部门意见：
                finalMap.put("后勤content", "\n4.后勤保障部门意见：\n");
                finalMap.put("content1", "☑ 已确认搬运路线通畅，可提供" + variables.get("support5") + "（如：专业搬运工具、电工支持），保障移动安全。");
                finalMap.put("content2", "\n审批人签字：");
                finalMap.put("content3", "\n部门负责人签字：");
                finalMap.put("content4", "\n日期：");
                List<Map<String, String>> signature_act5 = (List<Map<String, String>>) variables.get("signature_act5");
                finalMap.put("后勤审批人签字", Pictures.ofLocal(replaceUrl(signature_act5.get(0).get("url"))).size(200, 80).create());
                config.customPolicy("后勤审批人签字", new PictureRenderPolicy());
                List<Map<String, String>> leaderSign_act5 = (List<Map<String, String>>) variables.get("leaderSign_act5");
                finalMap.put("后勤部门负责人签字", Pictures.ofLocal(replaceUrl(leaderSign_act5.get(0).get("url"))).size(200, 80).create());
                config.customPolicy("后勤部门负责人签字", new PictureRenderPolicy());
                finalMap.put("后勤签字日期", variables.get("date5"));
            }

            //${specialAttr.contains("精密仪器") || specialAttr.contains("大型设备")}
            if (specialAttr.contains("精密仪器") || specialAttr.contains("大型设备")) {
                //6、设备科 / 技术部门意见
                String assessment6 = variables.get("assessment6").toString();
                if (StringUtils.isNotEmpty(assessment6)) {
                    finalMap.put("设备content", "\n5.设备科 / 技术部门意见：\n");
                    finalMap.put("content5", "☑ 已评估设备移动风险，建议采取" + variables.get("protectSuggest") + "防护措施（如：防震包装、专业调试），移动后将协助完成校准。\n");
                    finalMap.put("content6", "设备负责人签字：");
                    finalMap.put("content7", "\n部门负责人签字：");
                    finalMap.put("content8", "\n日期：");

                    List<Map<String, String>> signature_act6 = (List<Map<String, String>>) variables.get("signature_act6");
                    finalMap.put("设备负责人签字", Pictures.ofLocal(replaceUrl(signature_act6.get(0).get("url"))).size(200, 80).create());
                    config.customPolicy("设备负责人签字", new PictureRenderPolicy());
                    List<Map<String, String>> leaderSign_act6 = (List<Map<String, String>>) variables.get("leaderSign_act6");
                    finalMap.put("设备部门负责人签字", Pictures.ofLocal(replaceUrl(leaderSign_act6.get(0).get("url"))).size(200, 80).create());
                    config.customPolicy("设备部门负责人签字", new PictureRenderPolicy());
                    finalMap.put("设备签字日期", variables.get("date6"));
                }
            }

            String situation7_1 = variables.get("situation7_1").toString();
            if (situation7_1.equals("完好无损")) finalMap.put("设备状态确认1", "☑ 完好无损");
            else finalMap.put("设备状态确认1", "□ 完好无损");
            if (situation7_1.equals("轻微损伤"))
                finalMap.put("设备状态确认2", "☑ 轻微损伤（损伤情况：" + variables.get("detailSituation7_1") + "）");
            else finalMap.put("设备状态确认2", "□ 轻微损伤");
            if (situation7_1.equals("严重损坏"))
                finalMap.put("设备状态确认3", "☑ 严重损坏（需维修：" + variables.get("detailSituation7_1") + "）");
            else finalMap.put("设备状态确认3", "□ 严重损坏");
        } else if (moveType.equals("临时借用")) {//7_2_1
            List<Map<String, String>> signature_act7_2_1 = (List<Map<String, String>>) variables.get("signature_act7_2_1");
            finalMap.put("移入验收人签字", Pictures.ofLocal(replaceUrl(signature_act7_2_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("移入验收人签字", new PictureRenderPolicy());
            List<Map<String, String>> leaderSign_act7_2_1 = (List<Map<String, String>>) variables.get("leaderSign_act7_2_1");
            finalMap.put("移入科室验收签字", Pictures.ofLocal(replaceUrl(leaderSign_act7_2_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("移入科室验收签字", new PictureRenderPolicy());
            finalMap.put("移入负责人签字日期", variables.get("date7_2_1"));

            finalMap.put("实际移动时间", variables.get("moveTime7_2").toString());
            finalMap.put("移动完成时间", variables.get("completeTime7_2").toString());

            List<Map<String, String>> signature_act4_1 = (List<Map<String, String>>) variables.get("signature_act4_1");
            finalMap.put("资产审批人签字", Pictures.ofLocal(replaceUrl(signature_act4_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("资产审批人签字", new PictureRenderPolicy());
            finalMap.put("资产签字日期", variables.get("date4_1"));

            String situation7_2 = variables.get("situation7_2").toString();
            if (situation7_2.equals("完好无损")) finalMap.put("设备状态确认1", "☑ 完好无损");
            else finalMap.put("设备状态确认1", "□ 完好无损");
            if (situation7_2.equals("轻微损伤"))
                finalMap.put("设备状态确认2", "☑ 轻微损伤（损伤情况：" + variables.get("detailSituation7_2") + "）");
            else finalMap.put("设备状态确认2", "□ 轻微损伤");
            if (situation7_2.equals("严重损坏"))
                finalMap.put("设备状态确认3", "☑ 严重损坏（需维修：" + variables.get("detailSituation7_2") + "）");
            else finalMap.put("设备状态确认3", "□ 严重损坏");
        } else if (moveType.equals("永久调拨")) {//7_1_1
            List<Map<String, String>> signature_act7_1_1 = (List<Map<String, String>>) variables.get("signature_act7_1_1");
            finalMap.put("移入验收人签字", Pictures.ofLocal(replaceUrl(signature_act7_1_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("移入验收人签字", new PictureRenderPolicy());
            List<Map<String, String>> leaderSign_act7_1_1 = (List<Map<String, String>>) variables.get("leaderSign_act7_1_1");
            finalMap.put("移入科室验收签字", Pictures.ofLocal(replaceUrl(leaderSign_act7_1_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("移入科室验收签字", new PictureRenderPolicy());
            finalMap.put("移入负责人签字日期", variables.get("date7_1_1"));

            finalMap.put("实际移动时间", variables.get("moveTime7_1").toString());
            finalMap.put("移动完成时间", variables.get("completeTime7_1").toString());

            List<Map<String, String>> signature_act4_1 = (List<Map<String, String>>) variables.get("signature_act4_1");
            finalMap.put("资产审批人签字", Pictures.ofLocal(replaceUrl(signature_act4_1.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("资产审批人签字", new PictureRenderPolicy());
            finalMap.put("资产签字日期", variables.get("date4_1"));

            String situation7_1 = variables.get("situation7_1").toString();
            if (situation7_1.equals("完好无损")) finalMap.put("设备状态确认1", "☑ 完好无损");
            else finalMap.put("设备状态确认1", "□ 完好无损");
            if (situation7_1.equals("轻微损伤"))
                finalMap.put("设备状态确认2", "☑ 轻微损伤（损伤情况：" + variables.get("detailSituation7_1") + "）");
            else finalMap.put("设备状态确认2", "□ 轻微损伤");
            if (situation7_1.equals("严重损坏"))
                finalMap.put("设备状态确认3", "☑ 严重损坏（需维修：" + variables.get("detailSituation7_1") + "）");
            else finalMap.put("设备状态确认3", "□ 严重损坏");
        } else if (moveType.equals("维修搬运")) {//7_3
            List<Map<String, String>> signature_act7_3 = (List<Map<String, String>>) variables.get("signature_act7_3");
            finalMap.put("移入验收人签字", Pictures.ofLocal(replaceUrl(signature_act7_3.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("移入验收人签字", new PictureRenderPolicy());
            List<Map<String, String>> leaderSign_act7_3 = (List<Map<String, String>>) variables.get("leaderSign_act7_3");
            finalMap.put("移入科室验收签字", Pictures.ofLocal(replaceUrl(leaderSign_act7_3.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("移入科室验收签字", new PictureRenderPolicy());
            finalMap.put("移入负责人签字日期", variables.get("date7_3"));

            finalMap.put("实际移动时间", variables.get("moveTime7_3").toString());
            finalMap.put("移动完成时间", variables.get("completeTime7_3").toString());

            List<Map<String, String>> signature_act4_2 = (List<Map<String, String>>) variables.get("signature_act4_2");
            finalMap.put("资产审批人签字", Pictures.ofLocal(replaceUrl(signature_act4_2.get(0).get("url"))).size(200, 80).create());
            config.customPolicy("资产审批人签字", new PictureRenderPolicy());
            finalMap.put("资产签字日期", variables.get("date4_2"));

            String situation7_3 = variables.get("situation7_3").toString();
            if (situation7_3.equals("完好无损")) finalMap.put("设备状态确认1", "☑ 完好无损");
            else finalMap.put("设备状态确认1", "□ 完好无损");
            if (situation7_3.equals("轻微损伤"))
                finalMap.put("设备状态确认2", "☑ 轻微损伤（损伤情况：" + variables.get("detailSituation7_3") + "）");
            else finalMap.put("设备状态确认2", "□ 轻微损伤");
            if (situation7_3.equals("严重损坏"))
                finalMap.put("设备状态确认3", "☑ 严重损坏（需维修：" + variables.get("detailSituation7_3") + "）");
            else finalMap.put("设备状态确认3", "□ 严重损坏");
        }


        template.render(finalMap);
        // 生成临时文件
        String tempFileName = "设备移动单_" + variables.get("assetNumber") + "_" + System.currentTimeMillis() + ".docx";
        File tempFile = new File(System.getProperty("java.io.tmpdir"), tempFileName);

        try {
            template.writeToFile(tempFile.getAbsolutePath());
            log.info("Word文档生成成功，临时文件路径: {}", tempFile.getAbsolutePath());
            // 上传文件
            return uploadWordFile(tempFile, tempFileName);
            //本地路径
//            String wordPath = "D:\\项目学习\\若依工作流\\word\\aa.docx";
//            template.writeToFile(wordPath);
//            System.out.println("Word文档生成成功！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            template.close();

        }
    }
}
